package com.guyaning.deyson_core.core.ui.loader;

import android.content.Context;

import com.wang.avi.AVLoadingIndicatorView;
import com.wang.avi.Indicator;

import java.util.WeakHashMap;

/**
 * Created by Administrator on 2018/4/18.
 */

public final  class LoaderCreator {

    private static final WeakHashMap<String,Indicator>   LOADING_MAP = new WeakHashMap<>();

    public  static AVLoadingIndicatorView create(String type, Context context){

        final AVLoadingIndicatorView avLoadingIndicatorView = new AVLoadingIndicatorView(context);

        if(LOADING_MAP.get(type)==null){
          //创建
            final Indicator indicator = getIndicator(type);
            LOADING_MAP.put(type,indicator);
        }

        avLoadingIndicatorView.setIndicator(LOADING_MAP.get(type));

        return avLoadingIndicatorView;
    }

    private static Indicator getIndicator(String name){
        if(name == null || name.isEmpty()){
           return null;
        }

        final StringBuilder  drawableClassName = new StringBuilder();

        if(!name.contains(".")){
            final  String defultPackageName = AVLoadingIndicatorView.class.getPackage().getName();
            drawableClassName.append(defultPackageName)
                             .append(".indicators")
                             .append(".");
        }

        drawableClassName.append(name);

        try {
            Class<?>  drawableClass = Class.forName(drawableClassName.toString());

            return (Indicator) drawableClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
